package com.orange.cetback.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.cetback.common.exception.BaseException;
import com.orange.cetback.common.exception.SiliconFlowException;
import com.orange.cetback.common.properties.SiliconProperties;
import com.orange.cetback.pojo.dto.SiliconChatDTO;
import com.orange.cetback.pojo.vo.SiliconChatResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

// SiliconFlowUtil.java
@Slf4j
@Component
@RequiredArgsConstructor
public class SiliconFlowUtil {
    private final SiliconProperties siliconProperties;

    //流式输出
    public void streamChatCompletion(SiliconChatDTO dto, SseEmitter emitter) {
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", generateAuthHeader());
            headers.put("Accept", "text/event-stream"); // 关键头信息
            headers.put("Cache-Control", "no-cache");
            headers.put("Connection", "keep-alive");

            HttpClientUtil.doStreamPost(
                    siliconProperties.getChatEndpoint(),
                    headers,
                    buildRequestBody(dto),
                    line -> handleStreamData(line, emitter)
            );
        } catch (Exception e) {
            log.error("流式请求失败", e);
            emitter.completeWithError(new SiliconFlowException("流式对话服务异常"));
        }
    }

    private void handleStreamData(String line, SseEmitter emitter) {
        try {
            if (line.startsWith("data: ")) {
                String json = line.substring(6).trim();

                if ("[DONE]".equals(json)) {
                    emitter.send(SseEmitter.event().name("end").data(""));
                    emitter.complete();
                    return;
                }

                JSONObject response = JSON.parseObject(json);
                JSONObject delta = response.getJSONArray("choices")
                        .getJSONObject(0)
                        .getJSONObject("delta");

                if (delta.containsKey("content")) {
                    String content = delta.getString("content");
                    emitter.send(SseEmitter.event()
                            .data(content)
                            .id(UUID.randomUUID().toString()));
                } else {
                    // 发送心跳包保持连接
                    emitter.send(SseEmitter.event().comment("ping"));
                }
            }
        } catch (Exception e) {
            log.error("流数据处理异常", e);
            emitter.completeWithError(e);
        }
    }


    //没有流式输出
    public SiliconChatResponse chatCompletion(SiliconChatDTO dto) {
        try {
            // 1. 构造请求头
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", generateAuthHeader());
            headers.put("Content-Type", "application/json");

            // 2. 发送请求
            String response = HttpClientUtil.doPost(
                    siliconProperties.getChatEndpoint(),
                    headers,
                    buildRequestBody(dto)
            );

            // 3. 解析响应
            return parseResponse(response);
        } catch (Exception e) {
            log.error("对话接口调用失败", e);
            throw new BaseException("智能对话服务暂不可用");
        }
    }

    private String generateAuthHeader() {
        // 根据硅基实际鉴权方式生成（示例为简单API KEY模式）
        return "Bearer " + siliconProperties.getApiKey();
    }

    private String buildRequestBody(SiliconChatDTO dto) {
        JSONObject body = new JSONObject();
        JSONArray messagesArray = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", dto.getContent());
        messagesArray.add(message);
        body.put("messages", messagesArray);
        body.put("message", dto.getContent());
        body.put("model", "deepseek-ai/DeepSeek-V3");
        body.put("stream", true);
        body.put("max_tokens", 512);

        JSONArray stopArray = new JSONArray();
        stopArray.add("null");
        body.put("stop", stopArray);

        body.put("temperature", 0.7);
        body.put("top_p", 0.7);
        body.put("top_k", 50);
        body.put("frequency_penalty", 0.5);
        body.put("n", 1);

        JSONObject responseFormat = new JSONObject();
        responseFormat.put("type", "text");
        body.put("response_format", responseFormat);

        JSONArray toolsArray = new JSONArray();
        JSONObject tool = new JSONObject();
        tool.put("type", "function");

        JSONObject function = new JSONObject();
        function.put("description", "");
        function.put("name", "");
        function.put("parameters", new JSONObject());
        function.put("strict", false);

        tool.put("function", function);
        toolsArray.add(tool);
        body.put("tools", toolsArray);
        if (StringUtils.isNotBlank(dto.getSessionId())) {
            body.put("session_id", dto.getSessionId());
        }
        return body.toJSONString();
    }

    private SiliconChatResponse parseResponse(String jsonResponse)  throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        SiliconChatResponse response = mapper.readValue(jsonResponse, SiliconChatResponse.class);
        return response;
    }


}
